import SparkMD5 from 'spark-md5';

let util = {};

/**
 * 计算文件MD5
 * @param {Object} file    ----  文件
 * @param {Object} callback ---  计算结果回调
 */
util.fileMd5 = function(file, callback) {
	let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
	let chunkSize = 2097152;
	let chunks = Math.ceil(file.size / chunkSize);
	let currentChunk = 0;
	let spark = new SparkMD5.ArrayBuffer();
	let fileReader = new FileReader();
	fileReader.onload = function(e) {
		console.log('read chunk nr', currentChunk + 1, 'of', chunks);
		spark.append(e.target.result);
		currentChunk++;
		if(currentChunk < chunks) {
			loadNext();
		} else {
			console.log('finished loading');
			let md5value = spark.end();
			callback(md5value);
		}
	};
	fileReader.onerror = function() {
		console.warn('oops, something went wrong.');
	}

	function loadNext() {
		var start = currentChunk * chunkSize,
			end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

		fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
	}
	loadNext();
};

/**
 * 读取文件通过回调函数返回读取的BASE64的值
 * @param {Object} file
 * @param {Object} callback
 */
util.readFile = function(file, callback) {
	let fileReader = new FileReader();
	fileReader.readAsDataURL(file); 
	fileReader.onload = function() {  
		let result = fileReader.result;
		callback(result);
	}
}

/**
 * 读取文件通过回调函数返回读取的BASE64的值
 * @param {Object} file
 * @param {Object} callback
 */
util.readFileData = function(fileData, callback) {
	let file = fileData.file;
	let fileReader = new FileReader();
	fileReader.readAsDataURL(file); 
	fileReader.onload = function() {  
		let result = fileReader.result;
		fileData.result = result;
		callback(fileData);
	}
}

/**
 * //将base64转换为文件
 * @param {Object} dataurl
 * @param {Object} filename
 */
util.dataURLtoFile = function(dataurl, filename) {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

export default util;